const CacheManager = require("../template")

function testCacheManagerComplexScenarios() {
  console.log(
    "1. 复杂缓存系统测试:",
    (() => {
      const cache = new CacheManager(100)
      
      // 复杂缓存系统
      const cacheData = {
        'user:1': { id: 1, name: 'test1', email: 'test1@example.com' },
        'user:2': { id: 2, name: 'test2', email: 'test2@example.com' },
        'user:3': { id: 3, name: 'test3', email: 'test3@example.com' },
        'session:1': { userId: 1, token: 'token1', expires: Date.now() + 3600000 },
        'session:2': { userId: 2, token: 'token2', expires: Date.now() + 3600000 },
        'config:app': { theme: 'dark', lang: 'en', features: ['feature1', 'feature2'] }
      }
      
      // 设置缓存
      Object.entries(cacheData).forEach(([key, value]) => {
        cache.set(key, value)
      })
      
      // 验证缓存
      const user1 = cache.get('user:1')
      const session1 = cache.get('session:1')
      const config = cache.get('config:app')
      
      return user1.id === 1 &&
             session1.userId === 1 &&
             config.theme === 'dark'
    })()
  )

  console.log(
    "2. 缓存管理器动态负载测试:",
    (() => {
      const cache = new CacheManager(50)
      
      // 动态负载测试
      const loadPatterns = [
        { operation: 'set', key: 'load1', value: 100, ttl: 1000 },
        { operation: 'get', key: 'load1' },
        { operation: 'set', key: 'load2', value: 200, ttl: 2000 },
        { operation: 'get', key: 'load2' },
        { operation: 'set', key: 'load3', value: 300, ttl: 500 },
        { operation: 'get', key: 'load3' },
        { operation: 'cleanup' }
      ]
      
      let successCount = 0
      loadPatterns.forEach(pattern => {
        if (pattern.operation === 'set') {
          cache.set(pattern.key, pattern.value, pattern.ttl)
          successCount++
        } else if (pattern.operation === 'get') {
          const value = cache.get(pattern.key)
          if (value !== undefined) successCount++
        } else if (pattern.operation === 'cleanup') {
          const cleaned = cache.cleanup()
          successCount++
        }
      })
      
      return successCount >= 5
    })()
  )

  console.log(
    "3. 缓存管理器边界条件测试:",
    (() => {
      const cache = new CacheManager(10)
      
      // 边界条件测试
      const boundaryTests = [
        () => cache.set('', 'empty'), // 空键
        () => cache.set('key', null), // null值
        () => cache.set('key', undefined), // undefined值
        () => cache.get('nonexistent'), // 不存在的键
        () => cache.delete('nonexistent'), // 删除不存在的键
        () => cache.has('nonexistent'), // 检查不存在的键
        () => cache.setMaxSize(0), // 零大小
        () => cache.setMaxSize(-1) // 负大小
      ]
      
      let successCount = 0
      boundaryTests.forEach(test => {
        try {
          test()
          successCount++
        } catch (error) {
          // 某些操作可能失败
        }
      })
      
      return successCount >= 4 // 至少4个操作成功
    })()
  )

  console.log(
    "4. 缓存管理器错误恢复测试:",
    (() => {
      const cache = new CacheManager(10)
      
      try {
        // 错误恢复测试
        cache.set('error', 'initial')
        
        // 模拟错误
        try {
          cache.set('error', () => {
            throw new Error('Test error')
          })
        } catch (error) {
          // 错误被捕获
        }
        
        // 验证状态恢复
        const value = cache.get('error')
        return value === 'initial'
      } catch (error) {
        return false
      }
    })()
  )

  console.log(
    "5. 缓存管理器内存管理测试:",
    (() => {
      const cache = new CacheManager(100)
      
      // 内存管理测试
      const cacheCount = 200
      
      // 添加大量缓存
      for (let i = 0; i < cacheCount; i++) {
        cache.set(`key${i}`, `value${i}`)
      }
      
      const initialSize = cache.size()
      
      // 清理过期缓存
      const cleaned = cache.cleanup()
      
      const finalSize = cache.size()
      
      return initialSize <= 100 && // 不超过最大大小
             finalSize <= initialSize &&
             cleaned >= 0
    })()
  )

  console.log(
    "6. 缓存管理器并发操作测试:",
    (() => {
      const cache = new CacheManager(100)
      
      // 并发操作测试
      const operations = [
        () => cache.set('concurrent', 1),
        () => cache.get('concurrent'),
        () => cache.set('concurrent', 2),
        () => cache.get('concurrent'),
        () => cache.delete('concurrent'),
        () => cache.get('concurrent')
      ]
      
      operations.forEach(op => op())
      
      // 验证并发操作结果
      const finalValue = cache.get('concurrent')
      
      return finalValue === undefined // 应该被删除
    })()
  )

  console.log(
    "7. 缓存管理器复杂查询测试:",
    (() => {
      const cache = new CacheManager(100)
      
      // 添加复杂缓存
      const complexData = {
        'user:1': { id: 1, name: 'test1' },
        'user:2': { id: 2, name: 'test2' },
        'user:3': { id: 3, name: 'test3' },
        'session:1': { userId: 1, token: 'token1' },
        'session:2': { userId: 2, token: 'token2' }
      }
      
      Object.entries(complexData).forEach(([key, value]) => {
        cache.set(key, value)
      })
      
      // 复杂查询测试
      const userKeys = cache.keys().filter(key => key.startsWith('user:'))
      const sessionKeys = cache.keys().filter(key => key.startsWith('session:'))
      const allKeys = cache.keys()
      
      return userKeys.length === 3 &&
             sessionKeys.length === 2 &&
             allKeys.length === 5
    })()
  )

  console.log(
    "8. 缓存管理器状态一致性测试:",
    (() => {
      const cache = new CacheManager(100)
      
      // 状态一致性测试
      const operations = [
        () => cache.set('consistency', 1),
        () => cache.get('consistency'),
        () => cache.set('consistency', 2),
        () => cache.get('consistency'),
        () => cache.delete('consistency'),
        () => cache.get('consistency')
      ]
      
      const results = operations.map(op => op())
      
      return results[1] === 1 && // 设置后获取
             results[3] === 2 && // 更新后获取
             results[5] === undefined // 删除后获取
    })()
  )

  console.log(
    "9. this上下文复杂场景测试:",
    (() => {
      const complexObj = {
        multiplier: 3,
        processComplex: function(key, value) {
          const cache = new CacheManager()
          cache.set(key, value)
          return cache.get(key) * this.multiplier
        }
      }
      
      return complexObj.processComplex('test', 5) === 15
    })()
  )

  console.log(
    "10. 复杂对象this绑定复杂场景测试:",
    (() => {
      const complexConfigObj = {
        config: { threshold: 3 },
        processWithConfig: function(key, value) {
          const cache = new CacheManager()
          cache.set(key, value)
          return cache.get(key) >= this.config.threshold
        }
      }
      
      return complexConfigObj.processWithConfig('test', 5) === true
    })()
  )

  console.log(
    "11. 缓存管理器复杂操作序列测试:",
    (() => {
      const cache = new CacheManager(100)
      
      // 复杂操作序列
      const operationSequence = [
        { op: 'set', key: 'seq1', value: 1, ttl: 1000 },
        { op: 'set', key: 'seq2', value: 2, ttl: 2000 },
        { op: 'get', key: 'seq1' },
        { op: 'set', key: 'seq1', value: 3, ttl: 500 },
        { op: 'get', key: 'seq2' },
        { op: 'set', key: 'seq3', value: 4, ttl: 1500 },
        { op: 'get', key: 'seq3' },
        { op: 'cleanup' }
      ]
      
      let successCount = 0
      operationSequence.forEach(seq => {
        try {
          if (seq.op === 'set') {
            cache.set(seq.key, seq.value, seq.ttl)
          } else if (seq.op === 'get') {
            const value = cache.get(seq.key)
            if (value !== undefined) successCount++
          } else if (seq.op === 'cleanup') {
            const cleaned = cache.cleanup()
            successCount++
          }
          successCount++
        } catch (error) {
          // 某些操作可能失败
        }
      })
      
      return successCount >= 5 // 至少5个操作成功
    })()
  )

  console.log(
    "12. 缓存管理器复杂场景综合测试:",
    (() => {
      const cache = new CacheManager(100)
      
      // 综合复杂场景
      const scenarios = [
        // 场景1: 大量缓存设置
        () => {
          for (let i = 0; i < 100; i++) {
            cache.set(`scenario${i}`, i, 1000)
          }
          return cache.size() <= 100
        },
        // 场景2: 缓存获取
        () => {
          const value = cache.get('scenario0')
          return value === 0
        },
        // 场景3: 缓存更新
        () => {
          cache.set('scenario0', 100, 2000)
          return cache.get('scenario0') === 100
        },
        // 场景4: 缓存清理
        () => {
          const cleaned = cache.cleanup()
          return cleaned >= 0
        },
        // 场景5: 最终验证
        () => {
          const stats = cache.getStats()
          return stats.sets >= 100 && stats.hits >= 1
        }
      ]
      
      const results = scenarios.map(scenario => scenario())
      
      return results.every(result => result === true)
    })()
  )
}

testCacheManagerComplexScenarios()
